package com.gitee.fastmybatis.solon.spi;

import com.gitee.fastmybatis.core.ext.MapperRunner;
import com.gitee.fastmybatis.core.ext.code.util.FieldUtil;
import com.gitee.fastmybatis.core.ext.spi.MapperBuilder;
import org.noear.solon.core.AppContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author thc
 */
public class SolonContextMapperBuilder implements MapperBuilder {

    private static final Map<Class<?>, MapperRunner<?>> CACHE = new ConcurrentHashMap<>(64);


    @Override
    public <T> MapperRunner<T> getMapperRunner(Class<T> mapperClass, Object applicationContext) {
        return (MapperRunner<T>) CACHE.computeIfAbsent(mapperClass, k -> {
            AppContext ctx = (AppContext) applicationContext;
            T mapper;
            try {
                mapper = ctx.getBean(mapperClass);
            } catch (Exception e) {
                // 修复使用spring-boot-devtools导致获取不到实例
                String simpleName = mapperClass.getSimpleName();
                String beanName = FieldUtil.lowerFirstLetter(simpleName);
                mapper = (T) ctx.getBean(beanName);
            }
            return new MapperRunner<>(mapper, null);
        });


    }
}
